/*
 * @project_name:MUFareEngine
 * @Company (开发公司或单位)：印孚瑟斯技术(中国)有限公司
 * @Copyright © 2015 - 2999 CHINA EASTERN Limited
 */

package com.ceair.flight.refund.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;

/**
 * This class is used for DBUtil.
 * 
 * @author Infosys
 */
@Service("dbUtil")
public class DBUtil {
	
    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(DBUtil.class);

    /**
     * datasource.
     */
	@Autowired
	@Qualifier("dataSourceMybatis")
	private DataSource ds;
    
    /**
     * 
     * This method is used for batch update.
     *
     * @param sqlTemplate
     * @param list
     */
	public void batchUpdate(String sqlTemplate, List<Object[]> list) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = getDs().getConnection();
			ps = conn.prepareStatement(sqlTemplate);
			conn.setAutoCommit(false);
			int size = list.size();
			Object[] o = null;
			for (int i = 0; i < size; i++) {
				o = list.get(i);
				for (int j = 0; j < o.length; j++) {
					if (o[j] instanceof Date) {
						Date date = (Date) o[j];
						java.sql.Date sqlDate = new java.sql.Date(date
								.getTime());
						ps.setObject(j + 1, sqlDate);
					} else {
						ps.setObject(j + 1, o[j]);
					}

				}
				ps.addBatch();
			}
			ps.executeBatch();
			conn.commit();
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			LOGGER.error("batchUpdate fail.",e);
			try {
				conn.rollback();
				conn.setAutoCommit(true);
			} catch (SQLException e1) {
				LOGGER.error("batchUpdate fail.",e1);
			}
		} catch (Exception e) {
			LOGGER.error("batchUpdate fail.",e);
		} finally {
			try {
				DataSourceUtils.releaseConnection(conn,getDs());
			} catch (Exception e) {
				LOGGER.error("batchUpdate fail.",e);
			}

		}
	}

	/**
	 * @return the ds
	 */
	public DataSource getDs() {

		return ds;
	}

	/**
	 * @param ds the ds to set
	 */
	public void setDs(DataSource ds) {
		this.ds = ds;
	}

}
